<?php
/**
 * Created by PhpStorm.
 * User: HuangLuSen
 * Date: 2017/5/5
 * Time: 15:29
 */

namespace app\admin\model;


use think\Db;
use think\Model;

class AuthGroup extends Model
{
    protected $autoWriteTimestamp = 'int';

    /**
     * 状态获取器
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = [1 => '<span class="label label-success">启用</span>', 0 => '<span class="label label-danger">禁用'];
        return $status[$data['status']];
    }

    /**
     * 返回用户组列表
     * 默认返回正常状态的管理员用户组列表
     * @param array $where 查询条件,供where()方法使用
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getGroups($where = array())
    {
        $map = array('status' => 1, 'type' => 1);
        $map = array_merge($map, $where);
        return $this->where($map)->select();
    }

    /**
     * 返回用户所属用户组信息
     * @param  int $uid 用户id
     * @return array  用户所属的用户组 array(
     *                                         array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
     *                                         ...)
     */
    public function getUserGroup($uid)
    {
        static $groups = array();
        if (isset($groups[$uid]))
            return $groups[$uid];
        $prefix = config('prefix');
        $user_groups = Db::name('AuthGroup')->alias('a')->field('id,g.group_id,title,description,rules,mark')->join($prefix . "auth_group_access g", "a.id=g.group_id")->where("g.uid='$uid' and a.status='1'")->select();
        $groups[$uid] = $user_groups ? $user_groups : array();
        return $groups[$uid];
    }

    /**
     * * 检查用户组是否全部存在
     * @param array|string $gid 用户组id列表
     * @return bool
     */
    public function checkGroupId($gid)
    {
        return $this->checkId('AuthGroup', $gid, '以下用户组id不存在:');
    }

    /**
     * 检查id是否全部存在
     * @param $modelname
     * @param $mid
     * @param string $msg
     * @return bool
     */
    public function checkId($modelname, $mid, $msg = '以下id不存在:')
    {
        if (is_array($mid)) {
            $count = count($mid);
            $ids = implode(',', $mid);
        } else {
            $mid = explode(',', $mid);
            $count = count($mid);
            $ids = $mid;
        }
        $s = model($modelname)->where(array('id' => array('IN', $ids)))->column('id');
        if (count($s) === $count) {
            return true;
        } else {
            $diff = implode(',', array_diff($mid, $s));
            $this->error = $msg . $diff;
            return false;
        }
    }

    /**
     * 把用户添加到用户组,支持批量添加用户到用户组
     * 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
     * @param $uid
     * @param $gid
     * @return bool
     */
    public function addToGroup($uid, $gid)
    {
        $uid = is_array($uid) ? implode(',', $uid) : trim($uid, ',');
        $gid = is_array($gid) ? $gid : explode(',', trim($gid, ','));
        $Access = model('AuthGroupAccess');
        if (isset($_REQUEST['batch'])) {
            //为单个用户批量添加用户组时,先删除旧数据
            $del = $Access->where(array('uid' => array('in', $uid)))->delete();
        }
        $uid_arr = explode(',', $uid);
        $uid_arr = array_diff($uid_arr, array(1));
        $add = array();
        if ($del !== false) {
            foreach ($uid_arr as $u) {
//                //判断用户id是否合法
//                if (model('users')->getFieldByid($u, 'id') == false) {
//                    $this->error = "id为{$u}的用户不存在！";
//                    return false;
//                }
                foreach ($gid as $g) {
                    if (is_numeric($u) && is_numeric($g)) {
                        $add[] = array('group_id' => $g, 'uid' => $u);
                    }
                }
            }
            $Access->saveAll($add);
        }
        if ($Access->getError()) {
            if (count($uid_arr) == 1 && count($gid) == 1) {
                //单个添加时定制错误提示
                $this->error = "不能重复添加";
            }
            return false;
        } else {
            return true;
        }
    }
}